<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="消息标题" prop="title">
        <el-input v-model="searchForm.title" placeholder="请输入消息标题" clearable />
      </el-form-item>
      <el-form-item label="消息类型" prop="messageType">
        <el-select v-model="searchForm.messageType" placeholder="请选择消息类型" clearable style="width: 180px">
          <el-option label="系统通知" value="SYSTEM" />
          <el-option label="生产预警" value="PRODUCTION_ALERT" />
          <el-option label="质量预警" value="QUALITY_ALERT" />
          <el-option label="设备预警" value="EQUIPMENT_ALERT" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="searchForm.priority" placeholder="请选择优先级" clearable style="width: 180px">
          <el-option label="低" value="LOW" />
          <el-option label="中" value="MEDIUM" />
          <el-option label="高" value="HIGH" />
          <el-option label="紧急" value="URGENT" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px">
          <el-option label="草稿" value="DRAFT" />
          <el-option label="已发送" value="SENT" />
          <el-option label="已撤回" value="RECALLED" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增消息</el-button>
      <el-button type="success" :icon="Promotion" @click="handleBatchSend">批量发送</el-button>
      <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <el-table 
      :data="tableData" 
      style="width: 100%" 
      v-loading="loading" 
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="title" label="消息标题" show-overflow-tooltip />
      <el-table-column prop="messageType" label="消息类型">
        <template #default="scope">
          <el-tag :type="getMessageTypeTag(scope.row.messageType)">{{ getMessageTypeText(scope.row.messageType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级">
        <template #default="scope">
          <el-tag :type="getPriorityTag(scope.row.priority)">{{ getPriorityText(scope.row.priority) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="targetType" label="接收对象">
        <template #default="scope">
          <el-tag>{{ getTargetTypeText(scope.row.targetType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sendCount" label="发送数量" align="center">
        <template #default="scope">
          <el-badge :value="scope.row.sendCount" class="send-badge" />
        </template>
      </el-table-column>
      <el-table-column prop="readCount" label="已读数量" align="center">
        <template #default="scope">
          <el-badge :value="scope.row.readCount" class="read-badge" />
        </template>
      </el-table-column>
      <el-table-column prop="readRate" label="阅读率" align="center">
        <template #default="scope">
          <span :class="getReadRateClass(scope.row.readRate)">{{ scope.row.readRate }}%</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sender" label="发送人" />
      <el-table-column prop="sendTime" label="发送时间" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
          <el-button type="primary" link @click="handleEdit(scope.row)" v-if="scope.row.status === 'DRAFT'">编辑</el-button>
          <el-button type="success" link @click="handleSend(scope.row)" v-if="scope.row.status === 'DRAFT'">发送</el-button>
          <el-button type="warning" link @click="handleRecall(scope.row)" v-if="scope.row.status === 'SENT'">撤回</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
  </div>
</template>

<script setup lang="ts" name="messageManage">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Promotion, Delete } from "@element-plus/icons-vue";

const loading = ref(false);
const tableData = ref([]);
const searchFormRef = ref<FormInstance>();
const selectedRows = ref([]);

// 查询表单
const searchForm = reactive({
  title: "",
  messageType: "",
  priority: "",
  status: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 获取消息类型标签
const getMessageTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    SYSTEM: "primary",
    PRODUCTION_ALERT: "warning",
    QUALITY_ALERT: "danger",
    EQUIPMENT_ALERT: "info"
  };
  return typeMap[type] || "info";
};

// 获取消息类型文本
const getMessageTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    SYSTEM: "系统通知",
    PRODUCTION_ALERT: "生产预警",
    QUALITY_ALERT: "质量预警",
    EQUIPMENT_ALERT: "设备预警"
  };
  return typeMap[type] || type;
};

// 获取优先级标签
const getPriorityTag = (priority: string) => {
  const priorityMap: Record<string, string> = {
    LOW: "info",
    MEDIUM: "primary",
    HIGH: "warning",
    URGENT: "danger"
  };
  return priorityMap[priority] || "info";
};

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const priorityMap: Record<string, string> = {
    LOW: "低",
    MEDIUM: "中",
    HIGH: "高",
    URGENT: "紧急"
  };
  return priorityMap[priority] || priority;
};

// 获取接收对象文本
const getTargetTypeText = (targetType: string) => {
  const targetMap: Record<string, string> = {
    ALL: "全部用户",
    DEPARTMENT: "指定部门",
    ROLE: "指定角色",
    USER: "指定用户"
  };
  return targetMap[targetType] || targetType;
};

// 获取阅读率样式
const getReadRateClass = (rate: number) => {
  if (rate >= 80) return "read-rate-high";
  if (rate >= 50) return "read-rate-medium";
  return "read-rate-low";
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    DRAFT: "info",
    SENT: "success",
    RECALLED: "warning"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    DRAFT: "草稿",
    SENT: "已发送",
    RECALLED: "已撤回"
  };
  return statusMap[status] || status;
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: 1,
        title: "系统维护通知",
        messageType: "SYSTEM",
        priority: "HIGH",
        targetType: "ALL",
        sendCount: 150,
        readCount: 120,
        readRate: 80.0,
        status: "SENT",
        sender: "系统管理员",
        sendTime: "2024-01-15 10:30:00"
      },
      {
        id: 2,
        title: "生产线异常预警",
        messageType: "PRODUCTION_ALERT",
        priority: "URGENT",
        targetType: "DEPARTMENT",
        sendCount: 25,
        readCount: 23,
        readRate: 92.0,
        status: "SENT",
        sender: "张三",
        sendTime: "2024-01-15 14:15:00"
      },
      {
        id: 3,
        title: "质量检验结果通报",
        messageType: "QUALITY_ALERT",
        priority: "MEDIUM",
        targetType: "ROLE",
        sendCount: 0,
        readCount: 0,
        readRate: 0,
        status: "DRAFT",
        sender: "李四",
        sendTime: null
      },
      {
        id: 4,
        title: "设备保养提醒",
        messageType: "EQUIPMENT_ALERT",
        priority: "LOW",
        targetType: "USER",
        sendCount: 8,
        readCount: 5,
        readRate: 62.5,
        status: "SENT",
        sender: "王五",
        sendTime: "2024-01-14 16:45:00"
      }
    ];
    
    tableData.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error("获取消息列表失败:", error);
    ElMessage.error("获取消息列表失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 选择改变
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 新增消息
const handleAdd = () => {
  ElMessage.info("新增消息功能开发中");
};

// 批量发送
const handleBatchSend = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要发送的消息");
    return;
  }
  ElMessage.info("批量发送功能开发中");
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的消息");
    return;
  }
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条消息吗？`, "批量删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        ElMessage.success("批量删除成功");
        getTableData();
      } catch (error) {
        console.error("批量删除失败:", error);
        ElMessage.error("批量删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 查看详情
const handleView = (row: any) => {
  ElMessage.info(`查看消息 ${row.title} 详情`);
};

// 编辑消息
const handleEdit = (row: any) => {
  ElMessage.info(`编辑消息 ${row.title}`);
};

// 发送消息
const handleSend = async (row: any) => {
  ElMessageBox.confirm(`确认发送消息 "${row.title}" 吗？`, "发送确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info"
  })
    .then(async () => {
      try {
        ElMessage.success("消息发送成功");
        getTableData();
      } catch (error) {
        console.error("消息发送失败:", error);
        ElMessage.error("消息发送失败");
      }
    })
    .catch(() => {
      // 取消发送
    });
};

// 撤回消息
const handleRecall = async (row: any) => {
  ElMessageBox.confirm(`确认撤回消息 "${row.title}" 吗？`, "撤回确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        ElMessage.success("消息撤回成功");
        getTableData();
      } catch (error) {
        console.error("消息撤回失败:", error);
        ElMessage.error("消息撤回失败");
      }
    })
    .catch(() => {
      // 取消撤回
    });
};

// 删除消息
const handleDelete = async (row: any) => {
  ElMessageBox.confirm(`确认删除消息 "${row.title}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        ElMessage.success("消息删除成功");
        getTableData();
      } catch (error) {
        console.error("消息删除失败:", error);
        ElMessage.error("消息删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

.send-badge {
  margin-right: 10px;
}

.read-badge {
  margin-right: 10px;
}

.read-rate-high {
  color: #67c23a;
  font-weight: bold;
}

.read-rate-medium {
  color: #e6a23c;
  font-weight: bold;
}

.read-rate-low {
  color: #f56c6c;
  font-weight: bold;
}
</style>